"""
机器模型
"""
from sqlalchemy import Column, Integer, String, Enum, DateTime, Boolean, Text
from sqlalchemy.sql import func
from app.models.base import Base
from typing import Optional

class Machine(Base):
    """机器表模型"""
    __tablename__ = 't_machines'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='机器ID')
    name = Column(String(100), nullable=False, comment='服务器名称')
    ip = Column(String(45), unique=True, nullable=False, comment='IP地址')
    monitor_config = Column(Text, nullable=True, comment='监控配置(JSON格式)')
    status = Column(Enum('online', 'offline', 'warning', name='machine_status_enum'), nullable=False, default='offline', comment='状态')
    cpu = Column(Integer, nullable=False, default=0, comment='CPU使用率(%)')
    memory = Column(Integer, nullable=False, default=0, comment='内存使用率(%)')
    disk = Column(Integer, nullable=False, default=0, comment='磁盘使用率(%)')
    os = Column(String(100), nullable=True, comment='操作系统')
    purpose = Column(String(100), nullable=True, comment='用途')
    owner = Column(String(50), nullable=True, comment='负责人')
    location = Column(String(200), nullable=True, comment='机房位置')
    uptime = Column(String(50), nullable=True, comment='运行时长')
    last_reboot = Column(DateTime, nullable=True, comment='最后重启时间')
    is_activate = Column(Boolean, nullable=False, default=True, comment='是否激活: 1-是, 0-否')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=func.now(), onupdate=func.now(), comment='更新时间')
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'ip': self.ip,
            'monitor_config': self.monitor_config if self.monitor_config is not None else "",
            'status': self.status,
            'cpu': self.cpu,
            'memory': self.memory,
            'disk': self.disk,
            'os': self.os if self.os is not None else "",
            'purpose': self.purpose if self.purpose is not None else "",
            'owner': self.owner if self.owner is not None else "",
            'location': self.location,
            'uptime': self.uptime,
            'last_reboot': self.last_reboot.isoformat() if self.last_reboot is not None else None,
            'is_activate': self.is_activate,
            'created_at': self.created_at.isoformat() if self.created_at is not None else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at is not None else None
        }